package com.pdstudio.weather;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pdstudio.app.Application;
import com.pdstudio.bean.SimpleCity;
import com.pdstudio.bean.WeatherProfile;
import com.pdstudio.http.WeatherHttpMethod;
import com.pdstudio.util.SharePreferenceUtil;
import com.pdstudio.view.SwipeBackActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/*
 * 
 * 选择添加城市*/
public class AddCitysActivity1 extends SwipeBackActivity {

	public LayoutInflater inflater;
	private View customLiveIndexTitleView;
	private TextView txtTitle;

	//final String FOCUSCITYS = "focuscitys";// 存储的key
	//List<String> saveCitys;
	Map<String, WeatherProfile> weathers;// 城市code对应的实时天气
	List<SimpleCity> citys;//用来显示按钮，比关注的城市多了一个xo的city，这个是用来表示这里显示增加城市按钮用的
	Map<String,SimpleCity> foucusCitys;

	//SharedPreferences preferences; // 存储用户关注的城市
	//SharedPreferences.Editor editor;

	GridView gridview;
	private String currentCityCode = "";//记录要删除的城市

	private Handler handler;
	private Application mApplication;
	private SharePreferenceUtil mSpUtil;
	
	private ImageView ivBack;

	//用来获取当前长时间点击的城市，进行取消关注操作
	private synchronized void ChangeCurrentCityDel(String value) {
		this.currentCityCode = value;		
	}
	
	//用来保存当前单击的城市，用来做跳转，保存整个应用中当前选取的城市
	private synchronized void ChangeCurrentCity(String value){
		try{
			if(value!="xo"){
				SimpleCity s=mApplication.getSimpleCitys().get(value);
				mApplication.setCurSimpleCity(s);
			}
		}catch(Exception e){e.printStackTrace();}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_citys_main);
		
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		LinearLayout layout = (LinearLayout) findViewById(R.id.addcityslayout);
		int resId = mApplication.getApplicationBackground(mSpUtil
				.getWeatherStatus());
		layout.setBackground(getResources().getDrawable(resId));

		ivBack = (ImageView) findViewById(R.id.title2_back);
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AddCitysActivity1.this.finish();

			}

		});
		
		
		initalCitys();

		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					try {
						ProgressBar pb = (ProgressBar) findViewById(R.id.pb_add_city);
						pb.setVisibility(View.GONE);
						
					} catch (Exception e) {
						e.printStackTrace();
					}
					gridview.setAdapter(new AddCityAdapter());
				}
			}
		};

		inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);


		customLiveIndexTitleView = findViewById(R.id.title_photogallery);
		txtTitle = (TextView) customLiveIndexTitleView
				.findViewById(R.id.title2_text_nav);
		txtTitle.setText("城市添加");

		gridview = (GridView) findViewById(R.id.photogridview1);

		InitialView();
	}
	
	private void initalCitys(){
		try{
			Map<String,SimpleCity> ts=mApplication.getSharePreferenceUtil().getFocusCitys();
			citys=new ArrayList<SimpleCity>();
			for (Map.Entry<String, SimpleCity> entry:ts.entrySet()) {
				//citys.add(entry.getValue());
				TransFormCitys(entry.getValue());
			}
			SimpleCity s=new SimpleCity();
			s.cityCode="xo";
			s.cityId="xo";
			s.cityName="xo";
			//citys.add(s);
			TransFormCitys(s);
		}catch(Exception e){e.printStackTrace();}
	}

	//保证显示出来的城市没有异常，没有为空的
	protected void TransFormCitys(SimpleCity sc){
		List<SimpleCity> asc=new ArrayList<SimpleCity>();
		try{
			if(citys==null){
				citys=new ArrayList<SimpleCity>();
			}
			boolean isadd=true;
			if(sc!=null&&sc.cityCode!=null&&sc.cityCode!=""){
				for(int i=0;i<citys.size();i++){
					try{
						if(citys.get(i).cityCode==sc.cityCode){
							isadd=false;
						}
					}catch(Exception e){e.printStackTrace();}
				}
				if(isadd){
					citys.add(sc);
				}
				asc=citys;
				for(int i=0;i<citys.size();i++){
					try{
						if(citys.get(i).cityCode==null||citys.get(i).cityCode==""){
							asc.remove(citys.get(i));
						}
					}catch(Exception e){e.printStackTrace();}
				}
				citys=asc;
			}
		}catch(Exception e){e.printStackTrace();}
	}
	
	/*
	 * 获取天气的图标
	 */
	public int GetWeatherIcon(String climate) {
		int result = 0;
		try {
			result = mApplication.getWidgetWeatherIcon(climate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private void InitialView() {
		//saveCitys = new ArrayList<String>();
		initalCitys();
		weathers = new HashMap<String, WeatherProfile>();

		/*
		// 获取只能被本应用程序读、写的SharedPreferences对象
		preferences = getSharedPreferences(FOCUSCITYS, MODE_WORLD_READABLE);
		// 获得修改器
		editor = preferences.edit();
		try {
			String temp = preferences.getString(FOCUSCITYS, "");// 存储的城市用;分开
			if (temp != null && !temp.equals("")) {
				String[] temps = temp.split(";");
				if (temps != null && temps.length > 0) {
					for (int i = 0; i < temps.length; i++) {
						if (!saveCitys.contains(temps[i])) {
							saveCitys.add(temps[i]);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			saveCitys.add("xo");// 用来标记是添加按钮
		} catch (Exception e) {
			e.printStackTrace();
		}*///20141120废除，使用统一的sharepreference

		// 初始化天气信息
		try {
			Thread thread = new Thread() {
				@Override
				public void run() {
					WeatherHttpMethod hwm = new WeatherHttpMethod(
							getApplicationContext());
					if (citys != null) {
						for (int i=0;i<citys.size();i++) {
							WeatherProfile w = hwm.Getweatherforecasts(mApplication.getSharePreferenceUtil().getAuthCode(),
									citys.get(i).cityCode);
							if (citys.get(i).cityCode != "xo" && w != null
									&& !weathers.containsKey(citys.get(i).cityCode)) {
								weathers.put(citys.get(i).cityCode, w);
							}
						}
						Message m = new Message();
						m.what = 0;
						handler.sendMessage(m);
					}
				}
			};
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 复写onActivityResult，这个方法
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 可以根据多个请求代码来作相应的操作 10表示添加城市成功
		if (10 == resultCode) {
			InitialView();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public class AddCityAdapter extends BaseAdapter {

		private Context context;

		public void AddCityAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return citys.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return citys.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v = inflater.inflate(R.layout.activity_add_citys_main_item,
					null);
			try {
				String flag = citys.get(position).cityCode;// flag为x0时更换为添加按钮并注册单独的事件
				if (flag.equals("xo")) {
					LinearLayout tv1 = (LinearLayout) v
							.findViewById(R.id.add_city_linearlayout);
					tv1.setVisibility(View.INVISIBLE);
					ImageView add = (ImageView) v
							.findViewById(R.id.add_city_iv);
					add.setImageResource(R.drawable.addcity);
					add.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							// Toast.makeText(getApplicationContext(),
							// "this is add button", 0).show();
							Intent intent = new Intent(AddCitysActivity1.this,
									SearchCitysActivity.class);
							startActivityForResult(intent, 1);
						}

					});
				} else {
					TextView tv1 = (TextView) v
							.findViewById(R.id.phototextview1);
					tv1.setText(citys.get(position).cityName);
					TextView tv2 = (TextView) v
							.findViewById(R.id.phototextview2);
					tv2.setText(weathers.get(citys.get(position).cityCode) == null ? ""
							: weathers.get(citys.get(position).cityCode).weatherStatus);
					ImageView add = (ImageView) v
							.findViewById(R.id.add_city_iv);
					add.setImageResource(R.drawable.addcityback);
					add.setTag(citys.get(position).cityCode);

					ImageView wic = (ImageView) v
							.findViewById(R.id.add_city_iv_w);
					wic.setImageResource(GetWeatherIcon(weathers.get(citys
							.get(position).cityCode) == null ? "" : weathers
							.get(citys.get(position).cityCode).weatherStatus));

					TextView tvh = (TextView) v
							.findViewById(R.id.add_city_high_tem);
					tvh.setText(weathers.get(citys.get(position).cityCode) == null ? ""
							: weathers.get(citys.get(position).cityCode).highTemp);
					TextView tvl = (TextView) v
							.findViewById(R.id.add_city_low_tem);
					tvl.setText(weathers.get(citys.get(position).cityCode) == null ? ""
							: weathers.get(citys.get(position).cityCode).lowTemp);
					//ChangeCurrentCity(saveCitys.get(position));// 改变选中项的值
					
					add.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							ChangeCurrentCity(v.getTag().toString());
							
							Intent intent=new Intent(AddCitysActivity1.this,MainActivity.class);
							startActivity(intent);
							finish();
							
							//AddCitysActivity1.this.finish();
						}});
					
					add.setOnLongClickListener(new OnLongClickListener() {

						@Override
						public boolean onLongClick(View v) {
							// TODO Auto-generated method stub
							
							ChangeCurrentCityDel(v.getTag().toString());
							
							AlertDialog ad = new AlertDialog.Builder(
									AddCitysActivity1.this)
									.setTitle("取消关注")
									.setIcon(android.R.drawable.ic_dialog_info)
									.setMessage("是否取消关注该城市？")
									.setPositiveButton(
											"确定",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int whichButton) {
													// 这里添加点击确定后的逻辑
													// 删除
													try {
														Map<String,SimpleCity> temp=mApplication.getSharePreferenceUtil().getFocusCitys();
														if(temp!=null){
															temp.remove(currentCityCode);
														}
														mApplication.getSharePreferenceUtil().setFocusCitys(temp);
														Toast.makeText(
																AddCitysActivity1.this,
																"已取消该城市关注！",
																Toast.LENGTH_SHORT)
																.show();
														InitialView();
													} catch (Exception e) {
														e.printStackTrace();
														Toast.makeText(
																AddCitysActivity1.this,
																"取消关注失败！",
																Toast.LENGTH_SHORT)
																.show();
													}
												}
											}).setNegativeButton("返回", null)
									.show();

							return false;
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return v;
		}

	}

	// 长按菜单响应函数
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case 0:
			// 删除
			/*
			try {
				Map<String,SimpleCity> temp=mApplication.getSharePreferenceUtil().getFocusCitys();
				if(temp!=null){
					temp.remove(currentCityCode);
				}
				mApplication.getSharePreferenceUtil().setFocusCitys(temp);
				Toast.makeText(AddCitysActivity1.this, "已取消该城市关注！",
						Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(AddCitysActivity1.this, "取消关注失败！",
						Toast.LENGTH_SHORT).show();
			}*/

			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);

	}
}
